<template>
  <div class="app-container common-list-page">
    <el-container>
      <el-header>账户设置</el-header>
      <el-main>
        <el-form
          label-width="120px"
          :model="ruleForm"
          status-icon
          ref="ruleForm"
          :rules="resetFormRules"
          class="demo-ruleForm"
        >
          <!-- 头像 -->
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:88/api/oss"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemove"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <span
                v-if="imageUrl"
                class="el-upload-action"
                @click.stop="handleRemove()"
              >
                <i class="el-icon-delete"></i>
              </span>
              <i v-else class="el-icon-upload2 avatar-uploader-icon" stop></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="用户名：">
            <el-input
              disabled
              prop="username"
              v-model="ruleForm.username"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="邮箱：">
            <el-input v-model="ruleForm.email" disabled />
          </el-form-item>
          <el-form-item label="旧密码：" prop="password1">
            <el-input
              type="password"
              v-model="ruleForm.password1"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码：" prop="newpassword">
            <el-input
              type="password"
              v-model="ruleForm.newpassword"
              auto-complete="off"
            />
          </el-form-item>
          <el-form-item label="确认密码：" prop="password3">
            <el-input type="password" v-model="password" auto-complete="off" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >提交</el-button
            >
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>
<script>
export default {
  data() {
    var validatePass1 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入旧密码"));
      } else if (this.ruleForm.password1 !== this.ruleForm.password) {
        callback(new Error("旧密码不正确"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入新密码"));
      } else if (value.toString().length < 6 || value.toString().length > 18) {
        callback(new Error("密码长度为6-18位"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.resetForm.newpassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      imageUrl: "",
      files: [],
      saveBtnDisabled: true,
      ruleForm: {
        //传给后台所需要的参数
        username: "",
        email: "",
        password: ""
      },
      //表单验证规则
      resetFormRules: {
        password1: [
          { required: true, validator: validatePass1, trigger: "blur" }
        ],
        password: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ],
        newpassword: [
          { required: true, validator: validatePass, trigger: "blur" }
        ]
      },
      password: ""
    };
  },
  created() {
    // 页面渲染之前执行
    this.Initialization();
  },
  methods: {
    //初始化数据
    async Initialization() {
      const { data: res } = await this.$http.get(
        `vi/user/user/queryUsername/admin`
      );
      this.ruleForm = res.data.TbUserone;
      this.imageUrl = this.ruleForm.headPic;
    },
    // 移除图片
    handleRemove() {
      this.files = [];
      this.imageUrl = "";
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data.fileUrl;
      this.files.push(file);
    },
    // 上传前格式和图片大小限制
    beforeAvatarUpload(file) {
      const type =
        file.type === "image/jpeg" ||
        "image/jpg" ||
        "image/webp" ||
        "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!type) {
        this.$message.error("图片格式不正确!(只能包含jpg，png，webp，JPEG)");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return type && isLt2M;
    },
    //提交按钮
    async submitForm() {
      //设置头像
      this.ruleForm.headPic = this.imageUrl;
      //设置密码
      this.ruleForm.password = this.password;
      //这里的api.materialQuery.toAmend是调用前期我们统一的api接口url路径，不作参考 ，只要把后台需要的字段正常传进去即可
      const { data: res } = await this.$http.put(
        `vi/user/user/update`,
        this.ruleForm
      );
      //成功的回调
      if (res.code === 20000) {
        this.$message({
          type: "success",
          message: res.message
        });
        this.$router.push({
          //核心语句
          path: "/home", //跳转的路径
          query: {
            //路由传参时push和query搭配使用 ，作用时传递参数
            // templateId: row.id
          }
        });
      }
    }
  }
};
</script>
<style scoped lang="less">
.avatar-uploader {
  width: 100px;
  height: 100px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #eee;
}
.avatar-uploader-icon {
  box-sizing: border-box;
  font-size: 28px;
  color: #b7b7b7;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar-uploader-icon:hover {
  border: 1px dashed #b7b7b7;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.3);
}
.avatar {
  position: relative;
  width: 100px;
  height: 100px;
  display: block;
}
.el-upload-action {
  position: absolute;
  top: 0;
  left: 0;
  display: block;
  width: 100%;
  height: 100%;
  font-size: 0;
  color: #fff;
  text-align: center;
  line-height: 100px;
}
.el-upload-action:hover {
  font-size: 20px;
  background-color: #000;
  background-color: rgba(0, 0, 0, 0.3);
}
.el-form {
  width: 60%;
  margin: 50px auto 0;
  text-align: center;
  button {
    margin: 20px 0 0;
  }
}
.el-header,
.el-footer {
  background-color: #e0e4e9;
  color: #333;
  text-align: left;
  line-height: 60px;
}
</style>
